from sqlalchemy import func
from sqlalchemy.orm import relationship

from .auth import Auth
from ..database import database as db
class LocalAuth(db.Model):
    __table_name__ = 'local_auth'
    id = db.Column(db.Integer, primary_key=True)
    login_name = db.Column(db.String(40), nullable=False)
    password = db.Column(db.String(80), nullable=False)
    retry_count = db.Column(db.Integer, default=0)
    # profile_id = db.Column(db.String(100))
    auth_id = db.Column(db.ForeignKey(Auth.id))
    created_at = db.Column(db.DateTime, default=func.now())
    updated_at = db.Column(db.DateTime, default=func.now())
    type = db.Column(db.String(10), default='member')
    last_retry_time = db.Column(db.DateTime, nullable=True)

    auth = relationship(Auth)
    @classmethod
    def verify_password(cls, encrypted_password, password):
        return encrypted_password == cls.encrypt_password(password)

    @classmethod
    def encrypt_password(cls, password):
        import hashlib
        sha256 = hashlib.sha256()
        sha256.update(password.encode())
        return sha256.hexdigest()
